#include <iostream>
#include <vector>
#include <unistd.h>
#include "http_server.hpp"
#include "Log.hpp"
#include "Buffer.hpp"

using namespace ns_log;

void User(char *argv[])
{
    std::cout << argv[0] << " "
              << "port path" << std::endl;
}

int Write(const std::string &buf)
{
    std::string _data = "abcdefghijk";
    // 写
    buf.copy(const_cast<char *>(_data.c_str()) + 5, buf.size(), 0);
    LOG(INFO) << const_cast<char *>(_data.c_str()) + 5 << std::endl;
    LOG(INFO) << _data << std::endl;
    return 0;
}

void BufferInfo(Buffer *buf)
{
    std::cout << "capacity:" << buf->Capacity() << std::endl;
    std::cout << "writesize:" << buf->WriteAbleSize() << std::endl;
    std::cout << "readsize:" << buf->ReadAbleSize() << std::endl
              << std::endl;
}
void TestAppendData1(Buffer *buf, const std::string &s)
{
    buf->AppendData(s);
    std::cout << "AppendData" << std::endl;
    BufferInfo(buf);
}

void TestAppendData2(Buffer *buf, const char *s, int size)
{
    buf->AppendData(s, size);
    std::cout << "AppendData" << std::endl;
    BufferInfo(buf);
}

void TestSendData(Buffer *buf, int fd)
{
    buf->SendData(fd);
    BufferInfo(buf);
}

void TestReadLine(Buffer *buf)
{
    std::cout << "ReadLine:" << buf->ReadLine() << std::endl;
    BufferInfo(buf);
}

void TestBuffer()
{
    Buffer *wbuf = new Buffer(30);
    int fd = open("test3.gif", O_RDONLY);
    int wfd = open("test4.gif", O_WRONLY | O_CREAT);
    int count = 1;
    std::string s;
    while (count--)
    {
        char buf[1024] = {0};
        ssize_t sz = read(fd, buf, sizeof(buf));
        if (sz <= 0)
            break;
        std::cout << __LINE__ << ":" << sz << std::endl;
        // s += buf;
        // std::cout << __LINE__ << ":" << buf << std::endl;
        TestAppendData2(wbuf, buf, sz);
        TestSendData(wbuf, wfd);
    }
    std::cout << s << std::endl;
    close(fd);
    close(wfd);
}
struct Test1
{
    char a;
    // char b[3];
    char c;
};

void *rd(void *arg)
{
    char buf[4096];
    int fd = open("http_server.cpp", O_RDONLY);
    read(fd, buf, sizeof(buf));
    std::cout << pthread_self() << ":end\n";
}
#define TEST 0
int main(int argc, char *argv[])
{
#if TEST
    signal(SIGSEGV, &debug);
    pthread_t t1, t2;
    int ret1 = pthread_create(&t1, nullptr, rd, nullptr);
    std::cout << ret1;
    int ret2 = pthread_create(&t2, nullptr, rd, nullptr);
    std::cout << "12\n";
    sleep(10);
#else
    if (argc != 3)
    {
        User(argv);
        return -1;
    }
    // 更改服务器根目录
    chdir(argv[2]);

    HttpServer svr(atoi(argv[1]));
    svr.InitServer();
    svr.Run();
#endif
    return 0;
}